//
//  QXManager.swift
//  testZD
//
//  Created by 湛亚磊 on 2020/9/19.
//  Copyright © 2020 湛亚磊. All rights reserved.
//

import UIKit
import AVFoundation
import Photos
open class QXManager: NSObject {
    // 相册权限
    public class func photoAlbumPermissions(authorizedBlock: (()->())?, deniedBlock: (()->())?) {
        let authStatus = PHPhotoLibrary.authorizationStatus()
        
        // .notDetermined  .authorized  .restricted  .denied
        if authStatus == .notDetermined {
            // 第一次触发授权 alert
            PHPhotoLibrary.requestAuthorization { (status:PHAuthorizationStatus) -> Void in
                self.photoAlbumPermissions(authorizedBlock: authorizedBlock, deniedBlock: deniedBlock)
            }
            
        } else if authStatus == .authorized  {
            if authorizedBlock != nil {
                authorizedBlock!()
            }
        } else {
            if deniedBlock != nil {
                deniedBlock!()
            }
        }
    }
    /// 相机权限
    public class func cameraPermissions(authorizedBlock: (()->())?, deniedBlock: (()->())?) {
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        // .notDetermined  .authorized  .restricted  .denied
        if authStatus == .notDetermined {
            // 第一次触发授权 alert
            AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
                self.cameraPermissions(authorizedBlock: authorizedBlock, deniedBlock: deniedBlock)
            })
        } else if authStatus == .authorized {
            if authorizedBlock != nil {
                authorizedBlock!()
            }
        } else {
            if deniedBlock != nil {
                deniedBlock!()
            }
        }
    }
    
    /// 麦克风访问
    public class func microphonePermissions(authorizedBlock: (()->())?, deniedBlock: (()->())?) {
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)
        // .notDetermined  .authorized  .restricted  .denied
        if authStatus == .notDetermined {
            // 第一次触发授权 alert
            AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
                self.microphonePermissions(authorizedBlock: authorizedBlock, deniedBlock: deniedBlock)
            })
        } else if authStatus == .authorized {
            if authorizedBlock != nil {
                authorizedBlock!()
            }
        } else {
            if deniedBlock != nil {
                deniedBlock!()
            }
        }
    }
}
